package com.ailatrieuphu;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;

public class Connection extends AsyncTask<Message, Message, Connection> {
	private boolean mRun = false;
	private Socket socket = null;
	private DataInputStream dis;
	private DataOutputStream dao;

//	private final String SERVER_IP = "10.0.0.43";
	private final String SERVER_IP = "192.168.0.21";
	
	private final int SERVER_PORT = 9999;

	public Connection() {
 
	}

	public void sendMessage(Message message) {
		if (message == null || dao == null) {
			Log.e("messs",
					"Message dang null hoac DAO dang null -> khong gui duoc cmd");
			return;
		} 
		byte[] mess = message.getByteArrayBuffer();
		try {
			dao.write(mess);
			dao.flush();
		} catch (IOException e) {
			System.out.println("Khong gui duoc CMD: " + message.getCMD());
			e.printStackTrace();
		}

	}

	@Override
	protected Connection doInBackground(Message... params) {
		run();
		return null;
	}

	public boolean isConnecting() {
		return mRun;
	}

	public void closeSocket() {
		stopClient();
		try {
			if (dao != null)
				dao.close();
			if (dis != null)
				dis.close();
			if (socket != null)
				socket.close();
			dao = null;
			dis = null;
			socket = null;
		} catch (IOException e) {
			System.out.println("Close socket");
		}
	}

	public void stopClient() {
		System.out.println("Stop connect to server");
		mRun = false;
	}

	public boolean run() {
		mRun = true;
		Log.e("TCP Client", "C: Begin Connecting...");
		try {
			InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
			Log.e("TCP Client", "C: Connecting...");
			socket = new Socket(serverAddr, SERVER_PORT);
			try {
				dao = new DataOutputStream(socket.getOutputStream());
				Log.e("TCP Client", "C: Sent.");
				Log.e("TCP Client", "C: Done.");
				dis = new DataInputStream(socket.getInputStream());
				while (mRun) {
					int length = dis.readInt();
					byte[] data = new byte[length];
					dis.read(data);
					Message message2 = new Message(data);
					if (message2 != null) {
						Log.e("Received CMD", message2.getCMD() + "");
						GlobalHanldeMessage.processMessage(message2);
					}
				}
			} catch (Exception e) {
				Log.e("TCP", "S_Error : Socket cua ban close" + e);
				mRun = false;
			} finally {
				socket.close();
			}
		} catch (Exception e) {
			Log.e("TCP", "C_Error", e);
			MyActivity.instance.disConnection();
		}
		return false;
	}
}